﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Common.Web;
using CSP.Bll;
using CSP.Model.CSP;
using System.Collections.ObjectModel;
using CSP.Bll.IObjectBlls;
using Newtonsoft.Json;
using CSP.Common.Tools;
using CSP.Web.Master;
using CSP.Web.UserControls;

namespace CSP.Web.MyHome.Address
{
    public partial class Modify : CSPMyHome
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ((HomeMaster)Master).SelectedNavigationLink = MyHomeLeftNavigationLink.Address;
            if (!IsPostBack)
            {
                if (Request["parentid"] != null)
                {
                    int parentId = Convert.ToInt32(Request.QueryString["parentid"]);
                    string serviceTypeJson = GetServiceAreaJsonByParentId(parentId);
                    Response.ClearContent();
                    Response.Write(serviceTypeJson);
                    Response.ContentType = "text/plain";
                    Response.End();
                }
                else if (Request["parentsubid"] != null)
                {
                    int parentSubId = Convert.ToInt32(Request.QueryString["parentsubid"]);
                    string serviceTypeJson = GetServiceAreaJsonByParentId(parentSubId);
                    Response.ClearContent();
                    Response.Write(serviceTypeJson);
                    Response.ContentType = "text/plain";
                    Response.End();
                }
                else if (Request["modifyid"] != null)
                {
                    BindAddressUI();
                }
            }
        }


        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            UpdateAddress();
        }

        /// <summary>
        /// 绑定省市UI
        /// </summary>
        private void BindProvinceUI(string selectValue)
        {
            CSPBllFactory factory = CSPBllFactory.GetInstance();
            ICollection<ServiceArea> serviceAreas = new Collection<ServiceArea>();
            using (IServiceAreaBll serviceAreaBll = factory.GetServiceAreaBll())
            {
                serviceAreas = serviceAreaBll.FindByParentId(0);
            }
            this.S_Province.DataSource = serviceAreas.OrderBy(s => s.Orderid);
            this.S_Province.DataTextField = "name";
            this.S_Province.DataValueField = "id";
            this.S_Province.DataBind();
            this.S_Province.Items.Insert(0, new ListItem("请选择", ""));

            ListItem item = this.S_Province.Items.FindByValue(selectValue);
            if (item != null)
            {
                this.S_Province.SelectedIndex = -1;
                item.Selected = true;
            }
        }

        /// <summary>
        /// 绑定城市
        /// </summary>
        private void BindCityUI(int parentId, string selectValue)
        {
            CSPBllFactory factory = CSPBllFactory.GetInstance();
            ICollection<ServiceArea> serviceAreas = new Collection<ServiceArea>();
            using (IServiceAreaBll serviceAreaBll = factory.GetServiceAreaBll())
            {
                serviceAreas = serviceAreaBll.FindByParentId(parentId);
            }
            this.S_City.DataSource = serviceAreas.OrderBy(s => s.Orderid);
            this.S_City.DataTextField = "name";
            this.S_City.DataValueField = "id";
            this.S_City.DataBind();
            this.S_City.Items.Insert(0, new ListItem("请选择城市", ""));

            ListItem item = this.S_City.Items.FindByValue(selectValue);
            if (item != null)
            {
                this.S_City.SelectedIndex = -1;
                item.Selected = true;
            }
        }

        /// <summary>
        /// 绑定城镇UI
        /// </summary>
        private void BindCountyUI(int parentId, string selectValue)
        {
            CSPBllFactory factory = CSPBllFactory.GetInstance();
            ICollection<ServiceArea> serviceAreas = new Collection<ServiceArea>();
            using (IServiceAreaBll serviceAreaBll = factory.GetServiceAreaBll())
            {
                serviceAreas = serviceAreaBll.FindByParentId(parentId);
            }
            this.S_County.DataSource = serviceAreas.OrderBy(s => s.Orderid);
            this.S_County.DataTextField = "name";
            this.S_County.DataValueField = "id";
            this.S_County.DataBind();
            this.S_County.Items.Insert(0, new ListItem("请选择城镇", ""));

            ListItem item = this.S_County.Items.FindByValue(selectValue);
            if (item != null)
            {
                this.S_County.SelectedIndex = -1;
                item.Selected = true;
            }
        }

        /// <summary>
        /// 把将要修改的Address 数据绑定到web UI上
        /// </summary>
        private void BindAddressUI()
        {
            CSP.Model.CSP.Address address = GetModifyAddress();

            Txt_Name.Value = address.Name;
            Txt_Introduction.Text = address.Introduction;
            Txt_Province.Value = address.Province.ToString();
            Txt_City.Value = address.City.ToString();
            Txt_County.Value = address.County.ToString();
            Txt_Street.Value = address.Street;
            Txt_CN_Province.Value = address.CN_Province;
            Txt_CN_City.Value = address.CN_City;
            Txt_CN_County.Value = address.CN_County;
            Txt_Mobile.Value = address.Mobile;
            Txt_Phone.Value = address.Telephone;
            Txt_Email.Value = address.Email;

            foreach (Map map in address.Maps)
            {
                Txt_CenterPointX.Value = map.CenterPointX;
                Txt_CenterPointY.Value = map.CenterPointY;
                Txt_MarkerPointX.Value = map.MarkerPointX;
                Txt_MarkerPointY.Value = map.MarkerPointY;
                Txt_Zoom.Value = map.Zoom.ToString();
            }
            BindProvinceUI(address.Province.ToString());

            BindCityUI(address.Province, address.City.ToString());
            BindCountyUI(address.City.Value, address.County.ToString());
        }

        /// <summary>
        /// 获取将要修改的Address 数据
        /// </summary>
        private CSP.Model.CSP.Address GetModifyAddress()
        {
            CSP.Model.CSP.Address address = null;
            CSPBllFactory factory = CSPBllFactory.GetInstance();
            using (IAddressBll addressBll = factory.GetAddressBll())
            {
                address = addressBll.GetByIdAndUser(Convert.ToInt32(Request["modifyid"]), UserProvider.UserName);
            }
            return address;
        }

        /// <summary>
        /// 更新地址信息
        /// </summary>
        private void UpdateAddress()
        {

            CSPBllFactory factory = CSPBllFactory.GetInstance();
            using (IAddressBll addressBll = factory.GetAddressBll())
            {
                try
                {
                    CSP.Model.CSP.Address address = addressBll.GetByIdAndUser(Convert.ToInt32(Request["modifyid"]), UserProvider.UserName);
                    address = GetModifiedAddress(address);
                    addressBll.Update(address);

                }
                catch (Exception ex)
                {
                    LoggerProvider.Error(ex);
                    this.FailRedirect("提交未失败", "/MyHome/Address/List.aspx");
                }
            }

            this.SuccessfullRedirect("已经提交成功", "/MyHome/Address/List.aspx");
        }


        private string GetServiceAreaJsonByParentId(int parentId)
        {
            List<ServiceArea> serviceAreas = this.GetServiceAreaByParentId(parentId);
            List<ServiceAreaEntity> serviceAreasEntity = (from area in serviceAreas
                                                          select new ServiceAreaEntity
                                                          {
                                                              Id = area.Id,
                                                              Name = area.Name,
                                                              ParentId = area.Parentid
                                                          }).ToList();

            return JsonConvert.SerializeObject(serviceAreasEntity);
        }

        /// <summary>
        /// 从Bll层根据ParentId获取ServiceAreas
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<ServiceArea> GetServiceAreaByParentId(int parentId)
        {
            CSPBllFactory factory = CSPBllFactory.GetInstance();
            List<ServiceArea> result = new List<ServiceArea>();
            ICollection<ServiceArea> serviceAreas = null;
            using (IServiceAreaBll serviceAreaBll = factory.GetServiceAreaBll())
            {
                serviceAreas = serviceAreaBll.FindByParentId(parentId);
            }
            if (serviceAreas != null)
            {
                result = serviceAreas.ToList();
            }
            return result;
        }

        /// <summary>
        /// 获取修改过所需的address
        /// </summary>
        /// <returns></returns>
        private CSP.Model.CSP.Address GetModifiedAddress(CSP.Model.CSP.Address address)
        {
            address.UserName = UserProvider.UserName;
            address.Name = Txt_Name.Value;
            address.Introduction = Txt_Introduction.Text;
            address.Province = Convert.ToInt32(Txt_Province.Value);
            address.City = Convert.ToInt32(Txt_City.Value);
            address.County = Convert.ToInt32(Txt_County.Value);
            address.Street = Txt_Street.Value;
            address.CN_Province = Txt_CN_Province.Value;
            address.CN_City = Txt_CN_City.Value;
            address.CN_County = Txt_CN_County.Value;
            address.Mobile = Txt_Mobile.Value;
            address.Telephone = Txt_Phone.Value;
            address.Email = Txt_Email.Value;
            //address.LastModified = BitConverter.GetBytes(CommonTool.ConvertToTimeSpan(DateTime.Now)),
            address.Maps = GetModifiedMap(address.Maps);

            return address;
        }

        /// <summary>
        /// 获取要修改过的Map
        /// </summary>
        /// <returns></returns>
        private ICollection<Map> GetModifiedMap(ICollection<Map> maps)
        {

            foreach (Map map in maps)
            {
                map.CenterPointX = Txt_CenterPointX.Value;
                map.CenterPointY = Txt_CenterPointY.Value;
                map.MarkerPointX = Txt_MarkerPointX.Value;
                map.MarkerPointY = Txt_MarkerPointY.Value;
                map.Zoom = Convert.ToInt32(Txt_Zoom.Value);
            }


            return maps;
        }

        private class ServiceAreaEntity
        {
            public int Id { get; set; }

            public string Name { get; set; }

            public int ParentId { get; set; }
        }
    }
}